import ora from "ora";
import fs from "fs";
import {
  businessProjectRoot,
  getBusinessProjectFilePath,
  getThisProjectFilePath,
} from "../utils/index.js";
import rollupBuild from "./rollup.build.js";

/**
 * 编译打包
 * @param argv
 * @param options
 * @returns {Promise<{failed: boolean}>}
 */
const build = async (argv, options) => {
  const text = options.watch ? "编译中，等待文件变化..." : "开始编译...";
  const buildSpinner = ora(text);
  buildSpinner.start();
  console.log(" ");

  try {
    // 默认 rollup 配置文件地址
    const defaultRollupConfigFilePath = getThisProjectFilePath(
      "src/config/rollup.config.mjs"
    );
    // rollup 配置文件地址
    let rollupConfigFilePath = "";
    // 业务侧自定义的 rollup 配置文件地址
    const configValue = argv["c"] || argv["config"];
    const businessCustomRollupConfigFilePath = configValue
      ? getBusinessProjectFilePath(configValue)
      : "";
    if (configValue && fs.existsSync(businessCustomRollupConfigFilePath)) {
      rollupConfigFilePath = getBusinessProjectFilePath(configValue);
    } else {
      rollupConfigFilePath = defaultRollupConfigFilePath;
    }

    const rollupArgv = [];
    if (options.watch) {
      rollupArgv.push("-w");
    }

    // 编译
    const result = await rollupBuild(
      rollupConfigFilePath,
      businessProjectRoot,
      rollupArgv
    );

    buildSpinner.succeed("编译成功！");

    return result;
  } catch (err) {
    console.error(err);
    buildSpinner.fail("编译失败！");
    return {
      failed: true,
    };
  }
};
export default build;
